package com.jacksen.demo.view.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;

import com.jacksen.demo.view.R;
import com.jacksen.demo.view.fragments.dummy.ArticleBean;

/**
 *
 */
public class ArticleActivity extends AppCompatActivity implements HeadlinesFragment.OnChangeArticleListener {

    private FrameLayout frameLayout;

    private FragmentManager fragmentManager;

    private static final String TAG_ARTICLE = "TAG_ARTICLE";
    private ArticleFragment articleFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_fragments);

        init();
    }

    private void init() {
//        AssetFileDescriptor descriptor = getResources().openRawResourceFd(R.raw.xfermode);
//        FileDescriptor fileDescriptor = descriptor.getFileDescriptor();
//        descriptor.describeContents();
//        long length = descriptor.getLength();

        frameLayout = (FrameLayout) findViewById(R.id.article_frame_layout);

        fragmentManager = getSupportFragmentManager();

        articleFragment = ArticleFragment.newInstance();
        fragmentManager.beginTransaction().replace(R.id.article_frame_layout, articleFragment).commit();
    }

    @Override
    public void onChangeArticle(ArticleBean.ArticleItem item) {
        articleFragment = (ArticleFragment) fragmentManager.findFragmentByTag(TAG_ARTICLE);
        if (articleFragment != null) {
            articleFragment.updateArticleView(item);
        } else {
            articleFragment = ArticleFragment.newInstance(item.id, item.details);
            fragmentManager.beginTransaction().replace(R.id.article_frame_layout, articleFragment).commit();
        }
    }
}
